<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="isUpdate ? t('common.edit') : t('common.create')"
      @register="register"
      @ok="handleSubmit"
      @cancel="handleClose"
      :destroyOnClose="true"
      :minHeight="400"
      :width="600"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getPartClassPropForm } from './data';
  import {
    addPartFeatureList,
    updatePartFeatureList,
    UpdatePartTypePropSingle,
  } from '/@/api/demo/system';

  const { t } = useI18n();
  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();
  const isUpdate = ref(false);
  const docTypeId = ref('');
  const newIndex = ref(null);
  const canChange = ref('');
  const tableData = ref([]);
  const type = ref('');
  const currentRecord = ref<any>({});

  // 定义弹窗是否可见
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });

    // 解构 data 赋值
    const {
      type: typeVal,
      isUpdate: isUpdateVal,
      docTypeId: docId,
      newIndex: index,
      tableData: table,
      record,
    } = data;

    type.value = typeVal;
    isUpdate.value = !!isUpdateVal;
    docTypeId.value = docId;
    newIndex.value = index;
    tableData.value = table;
    currentRecord.value = record;
    setFieldsValue({ dispIndex: newIndex.value });

    if (!unref(isUpdate)) return;

    // 更新 canChange
    canChange.value = record.canChange;

    // 处理 attr 逻辑
    const attrMap = {
      '264': { readOnly: true, newAttr: '256' },
      '256': { readOnly: false },
      '392': { readOnly: true, newAttr: '384' },
      '384': { readOnly: false },
      '8456': { readOnly: true, newAttr: '8448' },
      '8448': { readOnly: false },
      '1288': { readOnly: true, newAttr: '1280' },
      '1280': { readOnly: false },
      '776': { readOnly: true, newAttr: '768' },
      '768': { readOnly: false },
    };

    // 更新 readOnly 和 attr
    const mapping = attrMap[record.attr];
    if (mapping) {
      record.readOnly = mapping.readOnly;
      record.attr = mapping.newAttr ?? record.attr;
    }

    // 转换 isOnly 和 pdmnull 为布尔值
    record.isOnly = record.isOnly == '1' || record.isOnly === true;
    record.pdmnull = record.pdmnull == '1' || record.pdmnull === true;

    setFieldsValue(record);
  });

  const [registerForm, { validate, setFieldsValue }] = useForm({
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
    schemas: getPartClassPropForm(isUpdate, canChange),
    showActionButtonGroup: false,
  });

  async function handleSubmit() {
    const values = await validate();
    console.log(values);
    // 判断是否有敏感属性
    if (!tableData.value.some((item) => item.isOnly === '1') && !values.isOnly) {
      return createMessage.warning(t('routes.demo.partSetting.sensitivePropertyAtLeastOne'));
    }

    // 处理 attr 映射
    const attrMap = { '256': '264', '384': '392', '8448': '8456', '1280': '1288', '768': '776' };
    values.attr = values.readOnly ? attrMap[values.attr] ?? values.attr : values.attr;
    Reflect.deleteProperty(values, 'readOnly');

    // 规范化布尔值字段
    values.isOnly = values.isOnly ? '1' : '0';
    values.pdmnull = values.pdmnull ? '1' : '0';

    // 处理 docTypeId 逻辑
    if (type.value === '零件分类') {
      values.docTypeId =
        currentRecord.value.isSelect == true || currentRecord.value.isSelect == '1'
          ? docTypeId.value
          : 'partRevision';
    } else {
      values.docTypeId = docTypeId.value;
    }

    values.canChange = unref(isUpdate) ? canChange.value : '1';

    // 处理 API 请求
    const apiMethod = unref(isUpdate)
      ? type.value === '零件分类'
        ? UpdatePartTypePropSingle
        : updatePartFeatureList
      : addPartFeatureList;

    try {
      setModalProps({ confirmLoading: true });
      await apiMethod(values);
      closeModal();
      emit('success');
      createMessage.success(t('common.saveSuccess'));
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  // 关闭弹窗
  const handleClose = () => {
    canChange.value = '';
    tableData.value = [];
    closeModal();
  };
</script>

<style lang="less" scoped></style>
